package com.songcan.oauth.controller;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.songcan.common.contans.CacheAuthContans;
import com.songcan.common.context.UserContext;
import com.songcan.common.exception.ParamNotException;
import com.songcan.common.utils.TreeUtil;
import com.songcan.common.vo.MenuVo;
import com.songcan.common.vo.UserDetailsNew;
import com.songcan.model.oauth.SysMenu;
import com.songcan.model.oauth.SysPosition;
import com.songcan.model.oauth.SysUser;
import com.songcan.oauth.service.SysDeptUserService;
import com.songcan.oauth.service.SysMenuService;
import com.songcan.oauth.service.SysPositionService;
import com.songcan.oauth.service.SysUserService;
import com.songcan.oauth.vo.UserRoleVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.bind.annotation.*;

import java.sql.Wrapper;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@AllArgsConstructor
@Slf4j
public class CommonController {



    private SysDeptUserService sysDeptUserService;
    private RedisTemplate redisTemplate;
    private SysUserService sysUserService;
    private SysMenuService sysMenuService;

    /**
     * 退出并删除token
     *
     */
    @DeleteMapping("/login-out")
    public void logout(@RequestHeader String Authorization) {
        String tokenValue = Authorization.replace(OAuth2AccessToken.BEARER_TYPE, StrUtil.EMPTY).trim();
         removeToken(tokenValue);
    }

    /**
     * 令牌管理调用
     *
     * @param token token
     */
    public void removeToken( String token) {
        RedisTokenStore redisTokenStore =new  RedisTokenStore(redisTemplate.getConnectionFactory());
        OAuth2AccessToken oAuth2AccessToken =redisTokenStore.readAccessToken(String.valueOf(token));


        OAuth2Authentication auth2Authentication = redisTokenStore.readAuthentication(oAuth2AccessToken);


        // 清空access token
        redisTokenStore.removeAccessToken(oAuth2AccessToken);

        // 清空 refresh token
        OAuth2RefreshToken refreshToken = oAuth2AccessToken.getRefreshToken();
        redisTokenStore.removeRefreshToken(refreshToken);
        redisTemplate.delete("AUTH:MENU:");
    }







    @GetMapping("/rest/info/me")
    public UserRoleVO get(){

        UserRoleVO userRoleVO = new UserRoleVO();
        SysUser sysUser = sysUserService.getById(Long.valueOf(UserContext.getUserId()));
        if(Objects.nonNull(sysUser)){

              userRoleVO.setUserId(sysUser.getUserId());
              userRoleVO.setRealName(sysUser.getName() == null?"未知":sysUser.getName());
              userRoleVO.setPhone(sysUser.getPhone());
              userRoleVO.setAvatarUrl(sysUser.getAvatar());
              userRoleVO.setSex(sysUser.getSex());

            List<String> roles =UserContext.getRoles();
            userRoleVO.setRoleCodes(roles);

            List<SysMenu> list = sysMenuService.selectMenuByUserId(roles,null,null);
            if(Objects.isNull(list)&&list.size()<1){
                throw new ParamNotException("对应角色角色不存在");
            }
            userRoleVO.setPermissions(list.parallelStream().map(SysMenu::getCode).collect(Collectors.toList()));
        }
        return userRoleVO;
    }



}
